const path = require("path");
const HTMLPlugin = require('html-webpack-plugin');
const webpack = require('webpack')
//const ExtractPlugin = require('extract-text-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const VueLoaderPlugin = require('vue-loader/lib/plugin');


//判断运行环境（生产环境还是运行环境）
const isDev = process.env.NODE_ENV === 'development';


const config = {
  target: 'web',
  entry: path.join(__dirname, 'src/index.js'),
  output: {
    filename: 'bundle.[hash:8].js',
    path: path.join(__dirname, 'dist')
  },
  plugins: [
    // make sure to include the plugin for the magic
    new VueLoaderPlugin(),

    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: isDev ? '"development"' : '"production"'
      }
    }),
    //生成html
    new HTMLPlugin()
  ],
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      },

      {
        test: /\.(gif|jpg|jpeg|png|svg)$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 1024,
            name: '[name]-aaa.[ext]'
          }
        }]
      }
    ]
  }
}

if (isDev) {
  config.module.rules.push({
    test: /\.styl$/,
    use: [
      'style-loader',
      'css-loader',
      {
        loader: "postcss-loader",
        options: {
          sourceMap: true
        }
      },
      'stylus-loader'
    ]
  })


  config.mode = 'development';
  config.devtool = '#cheap-module-eval-source-map';
  config.devServer = {
    port: 8000,
    host: '0.0.0.0',
    overlay: {
      errors: true
    },
    hot: true
  };
  config.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    //new webpack.NoEmitOnErrorsPlugin()
  );
  config.optimization = {
    //取代 new webpack.NoEmitOnErrorsPlugin()，编译错误时不打印输出资源。
    noEmitOnErrors: true
  }



} else {
  config.mode = 'production';

  config.entry = {
    app:path.join(__dirname, 'src/index.js'),
    vendor:['vue']
  };
  config.output.filename = '[name].[chunkhash:8].js';
  config.optimization = {
    minimize: true, //取代 new UglifyJsPlugin(/* ... */)
    providedExports: true,
    usedExports: true,
    //识别package.json中的sideEffects以剔除无用的模块，用来做tree-shake
    //依赖于optimization.providedExports和optimization.usedExports
    sideEffects: true,
    //取代 new webpack.optimize.ModuleConcatenationPlugin()
    concatenateModules: true,
    //取代 new webpack.NoEmitOnErrorsPlugin()，编译错误时不打印输出资源。
    noEmitOnErrors: true,

    splitChunks: {
      cacheGroups: {
        commons: {
          name: "vendor",
          test: /[\\/]node_modules[\\/]/,
          chunks: "initial",
          minChunks: 2
        },
        commons: {
          name: "runtime",
          chunks: "all",
          minChunks: 2
        }
      }
    }




  }

  config.module.rules.push({
    test: /\.styl$/,
    /*use: ExtractPlugin.extract({
      fallback: 'style-loader',
      use: [
        'css-loader',
        {
          loader: "postcss-loader",
          options: {
            sourceMap: true
          }
        },
        'stylus-loader'
      ]
    })*/

    use: [
      {
        loader:MiniCssExtractPlugin.loader // 提取css到外部文件中
      },
      'css-loader',
      {
        loader: "postcss-loader",
        options: {
          sourceMap: true
        }
      },
      'stylus-loader'
    ]
  });
  config.plugins.push(
    new MiniCssExtractPlugin({
      filename: "styles.[name].[contenthash].css",
      chunkFilename: "[id].[contenthash].css"
    }),

    //new ExtractPlugin('[contenthash:8].css')

    //new ExtractPlugin('styles.[md5:contenthash:hex:8].css')

    /*new webpack.optimize.CommonsChunkPlugin({
      name:'vendor'
    })*/
  );
}

module.exports = config;

